{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# <font color=\"#8c8c8c\">Tensorflow Exercise</font>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### <font color=\"#8c8c8c\">1. 什么是Tensorflow?</font>\n",
    "<font color=\"#8c8c8c\">TensorFlow 是一个编程系统, 使用图来表示计算任务. 图中的节点被称之为 op (operation 的缩写).  \n",
    "    \n",
    "一个 op 获得 0 个或多个 Tensor, 执行计算, 产生 0 个或多个 Tensor. 每个 Tensor 是一个类型化的多维数组.  \n",
    "\n",
    "例如, 你可以将一小组图像集表示为一个四维浮点数数组, 这四个维度分别是 [batch, height, width, channels]. \n",
    "\n",
    "一个 TensorFlow 图描述了计算的过程.为了进行计算, 图必须在 会话 里被启动.   \n",
    "\n",
    "会话将图的op分发到诸如 CPU 或 GPU之类的设备上,同时提供执行 op 的方法. \n",
    "\n",
    "这些方法执行后, 将产生的tensor返回. 在Python语言中,返回的 tensor 是 numpy ndarray 对象; 在C和C++语言中,返回的 tensor是 \n",
    "tensorflow::Tensor 实例.</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\ProgramData\\Anaconda3\\lib\\site-packages\\h5py\\__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.\n",
      "  from ._conv import register_converters as _register_converters\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建一个常量 op, 产生一个 1x2 矩阵. 这个 op 被作为一个节点\n",
    "# 加到默认图中.\n",
    "#\n",
    "# 构造器的返回值代表该常量 op 的返回值.\n",
    "matrix1 = tf.constant([[3.,3.]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor 'Const:0' shape=(1, 2) dtype=float32>"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "matrix1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建另外一个常量 op, 产生一个 2x1 矩阵.\n",
    "matrix2 = tf.constant([[2.],[2.]])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 创建一个矩阵乘法 matmul op , 把 'matrix1' 和 'matrix2' 作为输入.\n",
    "# 返回值 'product' 代表矩阵乘法的结果.\n",
    "product = tf.matmul(matrix1, matrix2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor 'MatMul:0' shape=(1, 1) dtype=float32>"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "product"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### <font color=\"#8c8c8c\">默认图现在有三个节点, 两个 constant() op, 和一个matmul() op. 为了真正进行矩阵相乘运算, 并得到矩阵乘法的 结果, 你必须在会话里启动这个图.</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 12.]]\n"
     ]
    }
   ],
   "source": [
    "# 启动默认图.\n",
    "sess = tf.Session()\n",
    "\n",
    "# 调用 sess 的 'run()' 方法来执行矩阵乘法 op, 传入 'product' 作为该方法的参数. \n",
    "# 上面提到, 'product' 代表了矩阵乘法 op 的输出, 传入它是向方法表明, 我们希望取回\n",
    "# 矩阵乘法 op 的输出.\n",
    "#\n",
    "# 整个执行过程是自动化的, 会话负责传递 op 所需的全部输入. op 通常是并发执行的.\n",
    "# \n",
    "# 函数调用 'run(product)' 触发了图中三个 op (两个常量 op 和一个矩阵乘法 op) 的执行.\n",
    "#\n",
    "# 返回值 'result' 是一个 numpy `ndarray` 对象.\n",
    "result = sess.run(product)\n",
    "print (result)\n",
    "# ==> [[ 12.]]\n",
    "\n",
    "# 任务完成, 关闭会话.\n",
    "sess.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color=\"#8c8c8c\">Session 对象在使用完后需要关闭以释放资源. 除了显式调用 close 外, 也可以使用 \"with\" 代码块 来自动完成关闭动作.</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[array([[ 12.]], dtype=float32)]\n"
     ]
    }
   ],
   "source": [
    "with tf.Session() as sess:\n",
    "  result = sess.run([product])\n",
    "  print (result)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<font color=\"#8c8c8c\">为了便于使用诸如 IPython 之类的 Python 交互环境, 可以使用 InteractiveSession 代替 Session 类, 使用 Tensor.eval() 和 Operation.run() 方法代替 Session.run(). 这样可以避免使用一个变量来持有会话.</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[-2. -1.]\n"
     ]
    }
   ],
   "source": [
    "sess1 = tf.InteractiveSession()\n",
    "\n",
    "x = tf.Variable([1.0, 2.0])\n",
    "a = tf.constant([3.0, 3.0])\n",
    "\n",
    "# 使用初始化器 initializer op 的 run() 方法初始化 'x' \n",
    "x.initializer.run()\n",
    "\n",
    "# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果 \n",
    "sub = tf.subtract(x, a)\n",
    "print (sub.eval())\n",
    "# ==> [-2. -1.]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## <font color=\"#8c8c8c\">Variables</font>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "1\n",
      "2\n",
      "3\n"
     ]
    }
   ],
   "source": [
    "# 创建一个变量, 初始化为标量 0.\n",
    "state = tf.Variable(0, name=\"counter\")\n",
    "\n",
    "# 创建一个 op, 其作用是使 state 增加 1\n",
    "one = tf.constant(1)\n",
    "new_value = tf.add(state, one)\n",
    "update = tf.assign(state, new_value)\n",
    "\n",
    "# 启动图后, 变量必须先经过`初始化` (init) op 初始化,\n",
    "# 首先必须增加一个`初始化` op 到图中.\n",
    "init_op = tf.global_variables_initializer()\n",
    "\n",
    "# 启动图, 运行 op\n",
    "with tf.Session() as sess:\n",
    "  # 运行 'init' op\n",
    "  sess.run(init_op)\n",
    "  # 打印 'state' 的初始值\n",
    "  print (sess.run(state))\n",
    "  # 运行 op, 更新 'state', 并打印 'state'\n",
    "  for _ in range(3):\n",
    "    sess.run(update)\n",
    "    print (sess.run(state))\n",
    "\n",
    "# 输出:\n",
    "\n",
    "# 0\n",
    "# 1\n",
    "# 2\n",
    "# 3"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "a = [[1,2,3],[4,5,6],[7,8,9],[10,11,12]]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3 3 3]\n",
      "[2 2 2 2]\n",
      "[5.5 6.5 7.5]\n",
      "[ 2.  5.  8. 11.]\n"
     ]
    }
   ],
   "source": [
    "with tf.Session() as sess:\n",
    "    b = tf.argmax(a, 0)\n",
    "    c = tf.argmax(a, 1)\n",
    "    d = tf.reduce_mean(tf.cast(a, tf.float32), 0)    \n",
    "    e = tf.reduce_mean(tf.cast(a, tf.float32), 1)\n",
    "\n",
    "    print(sess.run(b))    \n",
    "    print(sess.run(c))\n",
    "    print(sess.run(d))    \n",
    "    print(sess.run(e))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ True  True  True False False]]\n"
     ]
    }
   ],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
